<template>
  <div>
    <el-upload
        class="file-uploader"
        name="file"
        :data="{ fileType: Upload.FILETYPE.FILE, type: props.uploadType }"
        :headers="{ loginToken, appKey }"
        :action="Upload.URL"
        :on-change="handleUpload"
        :before-upload="beforeUpload"
    >
      <template #trigger>
        <el-button type="primary">上传文件</el-button>
      </template>
    </el-upload>
  </div>
</template>
<script setup name="FileUpload">
import {Upload} from "@/common/constant.js";
import {CacheUtil} from "@/utils/cacheUtil.js";
import useCurrentInstance from "@/hooks/useCurrentInstance.js";

const appKey = import.meta.env.VITE_APP_KEY;
const {proxy} = useCurrentInstance();
const emits = defineEmits(["uploadSuccess"])
const loginToken = CacheUtil.getToken();
const loading = ref(false);

const props = defineProps({
  uploadType: {
    type: String,
    required: true
  },
  fileSuffix: {
    type: [String],
    required: false
  }
})

function beforeUpload(file) {
  if (!props.fileSuffix) {
    return true;
  }
  let fileName = file.name;
  let pos = fileName.lastIndexOf('.');
  let lastName = fileName.substring(pos, fileName.length);
  if (lastName.toLowerCase() !== props.fileSuffix) {
    proxy.$message.error('文件必须为'+props.fileSuffix+'类型');
    return false;
  }
  return true;
}

function handleUpload(info) {
  if (info.status === 'uploading') {
    loading.value = false;
    return;
  }
  if (info.status === 'success') {
    if (info.response.success) {
      emits("uploadSuccess", info.response.data.filePath, props.uploadType);
    } else {
      proxy.$message.error(info.response.message);
    }
  }
  if (info.status === 'fail') {
    proxy.$message.error('上传失败');
  }
  loading.value = false;
}
</script>

<style scoped lang="scss">
:deep(.el-upload-list__item-file-name){
  max-width: 200px;
}
</style>